import jwt from 'jsonwebtoken'
import bcrypt from 'bcryptjs'
import { getUsers, addUser, updateUser, getUserById, createUserSession, getUserSessions, terminateUserSession, terminateAllUserSessions, validateUserSession } from './database'
import { log } from 'console'
import { CloudCog } from 'lucide-react'

// JWT配置 - 统一使用相同的密钥和配置
const JWT_SECRET = process.env.JWT_SECRET || 'your-super-secure-jwt-secret-key-at-least-64-characters-long'
const JWT_EXPIRES_IN = '7d'

export interface AuthUser {
  id: string
  email: string
  name: string
  avatar?: string
  role: 'USER' | 'ADMIN'
}

export interface LoginCredentials {
  email: string
  password: string
}

export interface RegisterData {
  email: string
  password: string
  name: string
}

/**
 * 密码哈希
 */
export async function hashPassword(password: string): Promise<string> {
  const saltRounds = 12
  return bcrypt.hash(password, saltRounds)
}

/**
 * 验证密码
 */
export async function verifyPassword(password: string, hashedPassword: string): Promise<boolean> {
  return bcrypt.compare(password, hashedPassword)
}

/**
 * 生成JWT令牌
 */
export function generateToken(user: AuthUser): string {
  return jwt.sign(
    {
      id: user.id,
      email: user.email,
      name: user.name,
      role: user.role
    },
    JWT_SECRET,
    { expiresIn: JWT_EXPIRES_IN }
  )
}

/**
 * 验证JWT令牌
 */
export function verifyToken(token: string): AuthUser | null {
  try {
    console.log('verifyToken', token, JWT_SECRET)
    const decoded = jwt.verify(token, JWT_SECRET) as any
    return {
      id: decoded.id,
      email: decoded.email,
      name: decoded.name,
      avatar: decoded.avatar,
      role: decoded.role
    }
  } catch (error) {
    console.error('Token verification failed:', error)
    return null
  }
}

/**
 * 用户注册
 */
export async function registerUser(data: RegisterData): Promise<{ success: boolean; user?: AuthUser; error?: string }> {
  try {
    // 验证输入
    if (!data.email || !data.password || !data.name) {
      return { success: false, error: '所有字段都是必填的' }
    }

    if (data.password.length < 6) {
      return { success: false, error: '密码长度至少6位' }
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
      return { success: false, error: '邮箱格式不正确' }
    }

    if (data.name.length < 2 || data.name.length > 50) {
      return { success: false, error: '姓名长度必须在2-50字符之间' }
    }

    // 检查邮箱是否已存在
    const users = await getUsers()
    const existingUser = users.find(u => u.email.toLowerCase() === data.email.toLowerCase())
    
    if (existingUser) {
      return { success: false, error: '该邮箱已被注册' }
    }

    // 创建新用户
    const hashedPassword = await hashPassword(data.password)
    const newUser = {
      id: crypto.randomUUID(),
      email: data.email.toLowerCase().trim(),
      name: data.name.trim(),
      password: hashedPassword,
      role: 'USER' as 'USER' | 'ADMIN'
    }

    await addUser(newUser)

    // 返回用户信息（不包含密码）
    const authUser: AuthUser = {
      id: newUser.id,
      email: newUser.email,
      name: newUser.name,
      role: newUser.role
    }

    return { success: true, user: authUser }
  } catch (error) {
    console.error('注册失败:', error)
    return { success: false, error: '注册失败，请重试' }
  }
}

/**
 * 用户登录
 */
export async function loginUser(credentials: LoginCredentials, ip?: string, userAgent?: string): Promise<{ success: boolean; user?: AuthUser; token?: string; error?: string }> {
  try {
    const { email, password } = credentials

    // 验证输入
    if (!email || !password) {
      return { success: false, error: '邮箱和密码不能为空' }
    }

    // 从数据库验证用户
    const users = await getUsers()
    const user = users.find(u => u.email === email)

    if (!user) {
      return { success: false, error: '用户不存在' }
    }

    // 验证密码（如果用户有密码字段）
    if (user.password) {
      const isValidPassword = await verifyPassword(password, user.password)
      if (!isValidPassword) {
        return { success: false, error: '密码错误' }
      }
    } else {
      // 如果没有密码字段，检查是否是默认用户
      if (password !== 'user123') {
        return { success: false, error: '密码错误' }
      }
    }

    // 构建认证用户对象（确保字段名一致）
    const authUser: AuthUser = {
      id: user.id,
      email: user.email,
      name: user.name,
      avatar: user.avatar,
      role: user.role as 'USER' | 'ADMIN'
    }

    // 生成JWT令牌
    const token = generateToken(authUser)
    
    // 创建用户会话
    try {
      const expiresAt = new Date()
      expiresAt.setDate(expiresAt.getDate() + 7) // 7天后过期
      
      await createUserSession({
        userId: user.id,
        token,
        ip: ip || null,
        userAgent: userAgent || null,
        expiresAt: expiresAt.toISOString(),
        isActive: true
      })
    } catch (sessionError) {
      console.error('创建用户会话失败:', sessionError)
      // 即使会话创建失败，也允许用户登录
    }

    return { success: true, user: authUser, token }
  } catch (error) {
    console.error('登录失败:', error)
    return { success: false, error: '服务器内部错误' }
  }
}

/**
 * 修改密码
 */
export async function changePassword(userId: string, currentPassword: string, newPassword: string): Promise<{ success: boolean; error?: string }> {
  try {
    // 验证输入
    if (!currentPassword || !newPassword) {
      return { success: false, error: '当前密码和新密码都是必填的' }
    }

    if (newPassword.length < 6) {
      return { success: false, error: '新密码长度至少6位' }
    }

    // 查找用户
    const users = await getUsers()
    const user = users.find(u => u.id === userId)

    if (!user || !user.password) {
      return { success: false, error: '用户不存在' }
    }

    // 验证当前密码
    const isValidPassword = await verifyPassword(currentPassword, user.password)
    if (!isValidPassword) {
      return { success: false, error: '当前密码错误' }
    }

    // 更新密码
    const hashedNewPassword = await hashPassword(newPassword)
    await updateUser(userId, { password: hashedNewPassword })

    return { success: true }
  } catch (error) {
    console.error('修改密码失败:', error)
    return { success: false, error: '修改密码失败，请重试' }
  }
}

/**
 * 获取用户信息
 */
export async function getUserInfo(userId: string): Promise<AuthUser | null> {
  try {
    const user = await getUserById(userId)
    
    if (!user) {
      return null
    }

    return {
      id: user.id,
      email: user.email,
      name: user.name,
      avatar: user.avatar,
      role: user.role
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

/**
 * 获取用户会话列表
 */
export async function getUserSessionList(userId: string): Promise<any[]> {
  try {
    const sessions = await getUserSessions(userId)
    
    // 格式化会话数据以便前端显示
    return sessions.map(session => ({
      id: session.id,
      ip: session.ip || '未知',
      userAgent: session.userAgent ? session.userAgent.substring(0, 50) + (session.userAgent.length > 50 ? '...' : '') : '未知',
      createdAt: session.createdAt,
      expiresAt: session.expiresAt,
      isActive: session.isActive,
      isCurrent: false // 需要在前端根据当前token判断
    }))
  } catch (error) {
    console.error('获取用户会话列表失败:', error)
    return []
  }
}

/**
 * 终止指定会话
 */
export async function terminateSession(sessionId: string, userId: string): Promise<boolean> {
  try {
    return await terminateUserSession(sessionId, userId)
  } catch (error) {
    console.error('终止会话失败:', error)
    return false
  }
}

/**
 * 终止所有会话（除了当前会话）
 */
export async function terminateAllSessions(userId: string, currentToken: string): Promise<number> {
  try {
    return await terminateAllUserSessions(userId, currentToken)
  } catch (error) {
    console.error('终止所有会话失败:', error)
    return 0
  }
}
